package com.lix.utils;

import com.alibaba.fastjson.JSONObject;
import com.lix.base.Token;
import com.lix.config.CommonConfig;
import com.lix.constant.CachePrefixContent;
import com.lix.constant.CommonContent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class UserUtils {

    private final JwtUtil jwtUtil;
    private final RedisUtil redisUtil;
    private final CommonConfig commonConfig;

    private UserUtils(JwtUtil jwtUtil, RedisUtil redisUtil, CommonConfig commonConfig) {
        this.jwtUtil = jwtUtil;
        this.redisUtil = redisUtil;
        this.commonConfig = commonConfig;
    }

    public String getUsername() {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse();

        // 暂时这么处理，正常情况下，只有login接口不存在ACCESS_TOKEN
        String accessTokenKey = request.getHeader(CommonContent.ACCESS_TOKEN);
        if (StringUtils.hasLength(accessTokenKey)) {
            String tokenStr = redisUtil.getString(redisUtil.getCacheKey(CachePrefixContent.TOKEN_PREFIX, accessTokenKey.trim()));
            Token token = null;
            try {
                token = jwtUtil.parseToken(tokenStr);
            } catch (Exception e) {
                log.info("获取用户登录用户名:用户已有token校验失败");
            }
            if (!ObjectUtils.isEmpty(token)) {
                String generateToken = jwtUtil.generateToken(token.getUser());
                redisUtil.set(redisUtil.getCacheKey(CachePrefixContent.TOKEN_PREFIX, accessTokenKey), generateToken, commonConfig.getValidityTime(), TimeUnit.MINUTES);
                Token parseToken = jwtUtil.parseToken(generateToken);
                log.info("UserUtils.getUsername获取到的用户名----{}", JSONObject.toJSONString(parseToken.getUser().getUsername()));
                return parseToken.getUser().getUsername();
            }
        } else {
            log.error("用户好像没有登录哟~~~");
        }
        return null;
    }

}
